<?php
/**
 * @title 264. 丑数 II - 穷列 + 最小堆
 * @author start2004
 */

class Solution {

    /**
     * @param Integer $n
     * @return Integer
     */
    function nthUglyNumber($n) {
        /**
         * @since 2020-07-30 最小堆
         */
        $heap = new SplMinHeap();
        $heap->insert(1);

        /**
         * @since 2020-07-30 穷列
         */
        $hashs = [];
        while($n>0){
            /**
             * @since 2020-07-30 移除最小值
             */
            $min = $heap->extract();
            // echo "n={$n}, min={$min}", PHP_EOL;

            /**
             * @since 2020-07-30 加入新的元素, 防止重复
             */
            foreach ([2,3,5] as $k){
                $val = $k*$min;
                if(!isset($hashs[$val])){
                    $heap->insert($val);
                    $hashs[$val] = 1;
                } else {}
            }
            $n--;
        }

        /**
         * @return
         */
        return $min;
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.30_2.php
 */
$datas = [
    10,
    1690,
    5500,
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof(2);
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->nthUglyNumber($data);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
